
import React, { Component } from 'react';
import { Form, Input, Radio, DatePicker, Cascader, Select, Button,Tooltip,InputNumber } from 'antd';
import { connect } from 'dva';
import * as ajax from "../../../services/api";
import './less/personnel.less';
import moment from 'moment';
const FormItem = Form.Item;
const { Option } = Select;
const RadioGroup = Radio.Group;
const { TextArea } = Input;

@connect(state => ({
  profile: state.profile,
}))

@Form.create()


export default class DetailedInformationPage extends Component {
  constructor(props, context) {
    super(props, context);
    this.state = {
      confirmDirty: false,
      perId:'',
      nationList:[],//国籍下拉选择值
      educationList:[],//学历
      bloodList:[],//血型
      nationMoreList:[],//民族下拉选择
      politicalList:[],//政治面貌
      maritalList:[],//婚姻
      areas:[],//省市区
      basicInFormaationData:{
        idCardType:'',
        idCardNo:'',
        name:'',
        isIncumbency:'',
        sex:'',
        nation:'',
        birthday:'',
        firstWorkDay:'',
        perType:'',
        nationality:'',
        originPlace:'',
        education:'',
        mobilePhone:'',
        email:'',
        height:'',
        bloodType:'',
        politicalStatus:'',
        maritalStatus:'',
        residentProvince:'',
        residentCity:'',
        residentArea:'',
        residenceAddress:'',
        domicileProvince:'',
        domicileCity:'',
        domicileArea:'',
        domicileAddress:'',
        contactper:'',
        contactPhone:'',
        perSource:'',
        remark:'',
        drivingLicenseLevel:'',
      },
      specialInformationData:[],//特殊字段
      drivingList:[],//驾照选择
      text:[],
      perIndFieldId:'',
    };
  }

  componentDidMount() {
    console.log('id的值',this.props.perId);
    console.log('props的值',this.props);
    this.setState({
      perId:this.props.perId,
    });
    ajax.systemPerBaseInfoGetPerBaseInfo({perId:this.props.perId}).then((data)=>{
      console.log('值值值值',data.data);
       if(data.data){
         this.setState({
           basicInFormaationData:data.data,
         },()=>{
           console.log('出生日期',this.state.basicInFormaationData.height)
         })
       }
    });
    ajax.systemConfigPerIndustryFindListByComId({perId:this.props.perId}).then((data)=>{
      console.log('值2值2值2',data.data);
      if(data.data.length >= 1){
        this.setState({
          specialInformationData:[],
        },()=>{
          this.setState({
            specialInformationData:data.data,
            perIndFieldId:data.data[0].perIndFieldId || '',
          })
        });
      }
    });
    this.renderNation();
    this.renderEducation();
    this.renderBlood();
    this.renderNationMore();
    this.renderPolitical();
    this.renderMarital();
    this.getDistrict();
    this.renderDriving();
  }


  handleSubmit = (e) => {
    e.preventDefault();
    this.props.form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        values.birthday = values['birthday'].format("YYYY-MM-DD");
        if(values.height === ''){
          values.height = 0;
        }
        if(values.domicile[0] !=='' && values.domicile.length>1){
          values.domicileProvince = values.domicile[0].toString();
          values.domicileCity = values.domicile[1].toString();
          values.domicileArea = values.domicile[2].toString();
        }else{
          values.domicileProvince = 0;
          values.domicileCity = 0;
          values.domicileArea = 0;
        }
        delete values.domicile;
        if(values.resident.length > 1 && values.resident[0] !== ''){
          values.residentProvince = values.resident[0];
          values.residentCity = values.resident[1];
          values.residentArea = values.resident[2];
        }else{
          values.residentProvince = 0;
          values.residentCity = 0;
          values.residentArea = 0;
        }
        delete values.resident;
        values.perIndustryInfoList = [];
        if(values.diseaseHistory !== ''){
          values.perIndustryInfoList.push({
            fieldCode:"diseaseHistory",
            fieldValue:values.diseaseHistory,
            perIndFieldId:this.state.perIndFieldId,
          });
        }
        if(values.isVeteran !== '' && values.isVeteran !== undefined){
          values.perIndustryInfoList.push({
            fieldCode:"isVeteran",
            fieldValue:values.isVeteran,
            perIndFieldId:this.state.perIndFieldId,
          });
        }
        if(values.workMonths !== ''){
          values.perIndustryInfoList.push({
            fieldCode:"workMonths",
            fieldValue:values.workMonths,
            perIndFieldId:this.state.perIndFieldId,
          });
        }
        if(values.workYears !== ''){
          values.perIndustryInfoList.push({
            fieldCode:"workYears",
            fieldValue:values.workYears,
            perIndFieldId:this.state.perIndFieldId,
          });
        }
        delete values.diseaseHistory;
        delete values.isVeteran;
        delete values.workMonths;
        delete values.workYears;
        values.perIndustryInfoList = JSON.stringify(values.perIndustryInfoList);
        console.log('提交的数据: ', values);
      }
      values.perId = this.state.perId;
      ajax.systemPerBaseInfoUpdateDetailedInfo({...values}).then((data)=>{
        console.log(data.data);
      },(err)=>{
        console.log(err);
      })
    });
  };



  //国籍下拉选择
  renderNation = () => {
    ajax.getDictInformation({codeTypes: 'nationality'}).then((data) => {
      //判断获取数据是否为空
      if (data.data) {
        this.setState({
          nationList: data.data.nationality,
        });
      }
    });
  };
  nationList = () =>{
    return this.state.nationList.map((val, key) => {
      return <Option key={key} value={val.codeValue+""}>{val.label}</Option>;
    });
  };

  //学历下拉选择
  renderEducation = () => {
    ajax.getDictInformation({codeTypes: 'education'}).then((data) => {
      //判断获取数据是否为空
      if (data.data) {
        this.setState({
          educationList: data.data.education,
        });
      }
    });
  };
  educationList = () => {
    return this.state.educationList.map((val, key) => {
      return <Option key={key} value={val.codeValue+""}>{val.label}</Option>;
    });
  };

  //血型下拉选择
  renderBlood = () => {
    ajax.getDictInformation({codeTypes: 'bloodType'}).then((data) => {
      //判断获取数据是否为空
      if (data.data) {
        this.setState({
          bloodList: data.data.bloodType,
        });
      }
    });
  };
  bloodList = () =>{
    return this.state.bloodList.map((val, key) => {
      return <Option key={key} value={val.codeValue+""}>{val.label}</Option>;
    });
  };

  //民族下拉选择
  renderNationMore = () => {
    ajax.getDictInformation({codeTypes: 'nation'}).then((data) => {
      //判断获取数据是否为空
      if (data.data) {
        this.setState({
          nationMoreList: data.data.nation,
        });
      }
    });
  };
  nationMoreList = () => {
    return this.state.nationMoreList.map((val, key) => {
      return <Option key={key} value={val.codeValue+""}>{val.label}</Option>;
    });
  };

  //政治面貌下拉选择
  renderPolitical  = () => {
    ajax.getDictInformation({codeTypes: 'politicalStatus'}).then((data) => {
      //判断获取数据是否为空
      if (data.data) {
        this.setState({
          politicalList: data.data.politicalStatus,
        });
      }
    });
  };
  politicalList = () =>{
    return this.state.politicalList.map((val, key) => {
      return <Option key={key} value={val.codeValue+""}>{val.label}</Option>;
    });
  };

  //婚姻下拉选择
  renderMarital = () => {
    ajax.getDictInformation({codeTypes: 'maritalStatus'}).then((data) => {
      //判断获取数据是否为空
      if (data.data) {
        this.setState({
          maritalList: data.data.maritalStatus,
        });
      }
    });
  };
  maritalList = () => {
    return this.state.maritalList.map((val, key) => {
      return <Option key={key} value={val.codeValue+""}>{val.label}</Option>;
    });
  };

  //驾照下拉选择
  renderDriving = () => {
    ajax.getDictInformation({codeTypes: 'drivingLicenseLevel'}).then((data) => {
      //判断获取数据是否为空
      if (data.data) {
        this.setState({
          drivingList: data.data.drivingLicenseLevel,
        });
      }
    });
  };
  drivingList = () => {
    return this.state.drivingList.map((val, key) => {
      return <Option key={key} value={val.codeValue+""}>{val.label}</Option>;
    });
  };

  //省市区
  getDistrict = () => {
    ajax.getDistrictData().then((data) => {
      let areas = data.data.map((val) => {
          return {
            value: val.regionId,
            label: val.regionName,
            children:val.childs.map((valChild) => {
              return {
                value: valChild.regionId,
                label: valChild.regionName,
                children:valChild.childs.map((valChildChild) => {
                  return {
                    value: valChildChild.regionId,
                    label: valChildChild.regionName,
                  }
                })
              }
            })
          };
        }
      );
      //console.log('areas:'+JSON.stringify(areas));
      this.setState({
        areas: areas,
      });
    })
  };

  //特殊字段
  specialList = () => {
    return this.state.specialInformationData.map((val,key) =>{
      return (<div className="wed" key={key}>
        {this.renderForm(val)}
      </div>)
    });
  };

  checkPhone = (rule, value, callback) => {
    if (value && !(/^1[0-9]{10}$/).test(value)) {
      callback('请输入正确的紧急联系人手机号码！');
    } else {
      callback();
    }
  };

  renderSecrialData = (text) => {
    return text.map((val, key) => {
      return <Option key={key} value={val.codeValue+""}>{val.label}</Option>;
    });
  };

  //遍历特殊字段
  renderForm = (value) => {
    const { getFieldDecorator } = this.props.form;
    const formItemLayout = {
      labelCol: {
        xs: { span: 10 },
        sm: { span: 6 },
      },
      wrapperCol: {
        xs: { span: 12 },
        sm: { span: 7 },
      },
    };
    if(value.fieldType === '1'){
      return (<FormItem
        {...formItemLayout}
        label={value.fieldName}
      >
        {getFieldDecorator(`${value.fieldCode}`, {
          initialValue:`${value.fieldValue}`,
          rules: [{ required: false, message: `'请输入'+${value.fieldName}+'!'` }],
        })(
          <TextArea placeholder="请填写" style={{height:150}} maxLength={value.maxLength}/>
        )}
      </FormItem>)
    }else if(value.fieldType === '2'){
      return (
        <FormItem
          {...formItemLayout}
          label={value.fieldName}
        >
          {getFieldDecorator(`${value.fieldCode}`, {
            initialValue:`${value.fieldValue}`,
            rules: [
              { required: false, message: `'请选择'+${value.fieldName}+'!'` },
            ],
          })(
            <InputNumber className="width-400" />
          )}
        </FormItem>
      )
    }else if(value.fieldType === '3'){
      return (
        <FormItem
          {...formItemLayout}
          label={value.fieldName}
        >
          {getFieldDecorator(`${value.fieldCode}`, {
            initialValue:moment(`${value.fieldValue}`,'YYYY-MM-DD') || null,
            rules: [
              { required: false, message: `'请选择'+${value.fieldName}+'!'` },
            ],
          })(
            <DatePicker />
          )}
        </FormItem>
      )
    }else if(value.fieldType === '4'){
      return (
        <FormItem
          {...formItemLayout}
          label={value.fieldName}
        >
          {getFieldDecorator(`${value.fieldCode}`, {
            initialValue:`${value.fieldValue}`,
            rules: [
              { required: false, message: `'请选择'+${value.fieldName}+'!'` },
            ],
          })(
            <Select className="width-400" placeholder="请选择">
              {this.renderSecrialData(value.dictList)}
            </Select>
          )}
        </FormItem>
      )
    }
  };

  //身高比较
  checkHeight = (rule, value, callback) => {
    if (value && !(/^([1-9][0-9]\d{0,1})$/).test(value)) {
      callback('请输入正确的身高！');
    } else {
      callback();
    }
  };

  render() {
    const { getFieldDecorator } = this.props.form;

    const formItemLayout = {
      labelCol: {
        xs: { span: 10 },
        sm: { span: 6 },
      },
      wrapperCol: {
        xs: { span: 12 },
        sm: { span: 7 },
      },
    };
    const tailFormItemLayout = {
      wrapperCol: {
        xs: {
          span: 24,
          offset: 0,
        },
        sm: {
          span: 14,
          offset: 6,
        },
      },
    };

    return (
      <div className="DetailedInformationPage PersonnelGeneralStyle">
        <div className="general-main">
          <div className="from-box">
            <Form onSubmit={this.handleSubmit}>
              <FormItem
                {...formItemLayout}
                label="人员类别"
              >
                {getFieldDecorator('perType', {
                  initialValue:this.state.basicInFormaationData.perType,
                  rules: [
                    { required: true, message: '请选择' },
                  ],
                })(
                  <Select className="width-400" placeholder="请选择">
                    <Option value="1">普通保安员</Option>
                    <Option value="2">武装押运人员</Option>
                    <Option value="3">内勤人员</Option>
                  </Select>
                  )}
              </FormItem>
              {this.state.basicInFormaationData.birthday ? <FormItem
                {...formItemLayout}
                label="出生日期"
              >
                {getFieldDecorator('birthday', {
                  initialValue:moment(this.state.basicInFormaationData.birthday,'YYYY-MM-DD'),
                  rules: [
                    { required: true, message: '请选择出生日期' },
                  ],
                })(
                  <DatePicker className="width-400" />
                )}
              </FormItem> :
                <FormItem
                {...formItemLayout}
                label="出生日期"
              >
                {getFieldDecorator('birthday', {
                  rules: [
                    { required: true, message: '请选择出生日期' },
                  ],
                })(
                  <DatePicker className="width-400" />
                )}
              </FormItem>}
              <FormItem
                {...formItemLayout}
                label="性别"
              >
                {getFieldDecorator('sex', {
                  initialValue:this.state.basicInFormaationData.sex,
                  rules: [
                    { required: false, message: '请选择性别!' },
                  ],
                })(
                  <RadioGroup>
                    <Radio value="1">男</Radio>
                    <Radio value="2" style={{ "marginLeft": "46px" }}>女</Radio>
                  </RadioGroup>
                  )}
              </FormItem>
              <FormItem
                {...formItemLayout}
                label="国籍"
              >
                {getFieldDecorator('nationality', {
                  initialValue:this.state.basicInFormaationData.nationality,
                  rules: [
                    { required: true, message: '请选择国籍!' },
                  ],
                })(
                  <Select className="width-400" placeholder="请选择">
                    {this.nationList()}
                  </Select>
                  )}
              </FormItem>
              <FormItem
                {...formItemLayout}
                label="籍贯"
              >
                {getFieldDecorator('originPlace', {
                  initialValue:this.state.basicInFormaationData.originPlace,
                  rules: [{
                      required: false, message: '请输入籍贯!',
                    }],
                })(
                  <Input className="width-400" placeholder="请选择" maxLength="10"/>
                  )}
              </FormItem>
              <FormItem
                {...formItemLayout}
                label="学历"
              >
                {getFieldDecorator('education', {
                  initialValue:this.state.basicInFormaationData.education,
                  rules: [{
                    required: true, message: '请输入学历!',
                  }, {
                    validator: this.checkConfirm,
                  }],
                })(
                  <Select className="width-400" placeholder="请选择">
                    {this.educationList()}
                  </Select>
                  )}
              </FormItem>
              <FormItem
                {...formItemLayout}
                label="身高"
              >
                {getFieldDecorator('height', {
                  initialValue:this.state.basicInFormaationData.height,
                  rules: [{
                      required: false, message: '请输入身高!',
                    },{
                    validator:this.checkHeight,
                  }],
                })(
                    <Input style={{width:400}} placeholder="请填写" addonAfter="CM" maxLength="3"/>
                  )}
              </FormItem>
              <FormItem
                {...formItemLayout}
                label="血型"
              >
                {getFieldDecorator('bloodType', {
                  initialValue:this.state.basicInFormaationData.bloodType,
                  rules: [
                    { required: false, message: '请选择血型!' },
                  ],
                })(
                  <Select className="width-400" placeholder="请选择">
                    {this.bloodList()}
                  </Select>
                  )}
              </FormItem>
              <FormItem
                {...formItemLayout}
                label="民族"
              >
                {getFieldDecorator('nation', {
                  initialValue:this.state.basicInFormaationData.nation,
                  rules: [
                    { required: false, message: '请选择民族!' },
                  ],
                })(
                  <Select className="width-400" placeholder="请选择">
                    {this.nationMoreList()}
                  </Select>
                  )}
              </FormItem>
              <FormItem
                {...formItemLayout}
                label="政治面貌"
              >
                {getFieldDecorator('politicalStatus', {
                  initialValue:this.state.basicInFormaationData.politicalStatus,
                  rules: [
                    { required: false, message: '请选择政治面貌!' },
                  ],
                })(
                  <Select className="width-400" placeholder="请选择">
                    {this.politicalList()}
                  </Select>
                  )}
              </FormItem>
              <FormItem
                {...formItemLayout}
                label="婚姻状况"
              >
                {getFieldDecorator('maritalStatus', {
                  initialValue:this.state.basicInFormaationData.maritalStatus,
                  rules: [
                    { required: false, message: '请选择婚姻状况!' },
                  ],
                })(
                  <Select className="width-400" placeholder="请选择">
                    {this.maritalList()}
                  </Select>
                  )}
              </FormItem>
              {this.state.basicInFormaationData.residentProvince !== '' ?  <FormItem
                {...formItemLayout}
                label="家庭住址"
              >
                {getFieldDecorator('resident', {
                  initialValue:[parseInt(this.state.basicInFormaationData.residentProvince),parseInt(this.state.basicInFormaationData.residentCity),parseInt(this.state.basicInFormaationData.residentArea)],
                  rules: [{ type: 'array', required: false, message: '请选择你的家庭住址!' }],
                })(
                  <Cascader options={this.state.areas} placeholder="请选择" className="width-400"/>
                )}
              </FormItem> :
                <FormItem
                  {...formItemLayout}
                  label="家庭住址"
                >
                  {getFieldDecorator('resident', {
                    initialValue:['','',''],
                    rules: [{ type: 'array', required: false, message: '请选择你的家庭住址!' }],
                  })(
                    <Cascader options={this.state.areas} placeholder="请选择" className="width-400"/>
                  )}
                </FormItem>}
              <FormItem
                {...formItemLayout}
                label="详细地址"
              >
                {getFieldDecorator('residenceAddress', {
                  initialValue:this.state.basicInFormaationData.residenceAddress,
                  rules: [{
                      required: false, message: '请输入地址!',
                    }],
                })(
                  <Input className="width-400" placeholder="请填写身份证件详细地址" maxLength="20"/>
                  )}
              </FormItem>
              {this.state.basicInFormaationData.domicileProvince !== '' ?  <FormItem
                {...formItemLayout}
                label="居住住址"
              >
                {getFieldDecorator('domicile', {
                  initialValue:[parseInt(this.state.basicInFormaationData.domicileProvince),parseInt(this.state.basicInFormaationData.domicileCity),parseInt(this.state.basicInFormaationData.domicileArea)],
                  rules: [{ type: 'array', required: false, message: '请选择你的居住住址!' }],
                })(
                  <Cascader options={this.state.areas} placeholder="请选择" className="width-400"/>
                )}
              </FormItem> :
                <FormItem
                  {...formItemLayout}
                  label="居住住址"
                >
                  {getFieldDecorator('domicile', {
                    initialValue:['','',''],
                    rules: [{ type: 'array', required: false, message: '请选择你的居住住址!' }],
                  })(
                    <Cascader options={this.state.areas} placeholder="请选择" className="width-400"/>
                  )}
                </FormItem>}
              <FormItem
                {...formItemLayout}
                label="详细地址"
              >
                {getFieldDecorator('domicileAddress', {
                  initialValue:this.state.basicInFormaationData.domicileAddress,
                  rules: [{
                      required: false, message: '请输入地址!',
                    }],
                })(
                  <Input className="width-400" placeholder="请填写详细居住地址" maxLength="20"/>
                  )}
              </FormItem>
              <FormItem
                {...formItemLayout}
                label="紧急联系人"
              >
                {getFieldDecorator('contactper', {
                  initialValue:this.state.basicInFormaationData.contactper,
                  rules: [{
                      required: false, message: '请输入紧急联系人!',
                    }],
                })(
                  <Input className="width-400" placeholder="请填写" maxLength="10"/>
                  )}
              </FormItem>
              <FormItem
                {...formItemLayout}
                label="紧急联系人手机号"
              >
                {getFieldDecorator('contactPhone', {
                  initialValue:this.state.basicInFormaationData.contactPhone,
                  rules: [{ required: false, message: '' },
                  {
                    validator: this.checkPhone,
                  }
                  ],
                })(
                  <Input className="width-400" placeholder="请填写正确手机号码" maxLength="11"/>
                  )}
              </FormItem>
              <FormItem
                {...formItemLayout}
                label="驾照等级"
              >
                {getFieldDecorator('drivingLicenseLevel', {
                  initialValue:this.state.basicInFormaationData.drivingLicenseLevel,
                  rules: [
                    { required: false, message: '请选择驾照等级!' },
                  ],
                })(
                  <Select className="width-400" placeholder="请选择">
                    {this.drivingList()}
                  </Select>
                )}
              </FormItem>
              {this.specialList()}
              <FormItem {...tailFormItemLayout}>
                {/*<Button type="primary" htmlType="button" style={{ "backgroundColor": "#FFF", "color": "#666", "borderColor": "#ccc" }}>取消</Button>*/}
                <Button type="primary" htmlType="submit">保存</Button>
              </FormItem>
            </Form>
          </div>
        </div>
      </div>
    );
  }
}




